using System;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model._Admin;
using HengTong.Model.Db;
using HengTong.Model.Db.System;
using HengTong.Model.Extension;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TiaoTaoHelper.Wtm.Models;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;

namespace HengTong.ViewModel._Admin.SysUserJobPositionVms;

public partial class SysUserJobPositionVm
{
    public override async Task DoAddAsync()
    {
        var transaction = DC.BeginTransaction();
        try
        {
            if (Entity.UserId == null)
            {
                MSD.AddModelError("Entity.UserId", "用户不能为空");
                return;
            }

            if (Entity.IsMain)
            {
                await DC.Set<SysUserJobPosition>()
                    .Where(e => e.UserId == Entity.UserId)
                    .ExecuteUpdateAsync(e =>
                        e.SetProperty(x => x.IsMain, x => false));
                await DC.SaveChangesAsync();
            }

            await base.DoAddAsync();
            await UpdateUserGroupAsync(Entity.UserId.Value);
            await transaction.CommitAsync();
        }
        catch (Exception e)
        {
            var scope = Wtm.ServiceProvider.CreateScope();
            var logger = scope.ServiceProvider.GetRequiredService<ILogger<SysUserJobPositionVm>>();
            logger.LogError(e, $"用户新增岗位发生异常, {e.Message}");
            MSD.AddModelError(" ", $"编辑操作异常: {e.Message}");
            await transaction.RollbackAsync();
        }
        finally
        {
            await transaction.DisposeAsync();
        }
    }

    /// <summary>
    /// 更新用户组和权限信息
    /// </summary>
    /// <param name="userId"></param>
    /// <exception cref="Exception"></exception>
    public async Task UpdateUserGroupAsync(Guid userId)
    {
        var user = await DC.Set<FrameworkUser>()
            .AsNoTracking()
            .Where(e => e.ID == userId)
            .FirstOrDefaultAsync();
        if (user == null) throw new Exception("用户不存在");
        // 删除用户原有的组信息
        await DC.Set<FrameworkUserGroup>()
            .Where(e => e.UserCode == user.ITCode)
            .ExecuteDeleteAsync();
        // 添加用户新的组信息
        var groupCodeList = await DC.Set<SysUserJobPosition>()
            .AsNoTracking()
            .Where(e => e.UserId == userId)
            .Select(e => e.JobPosition.Group.GroupCode)
            .Distinct()
            .ToListAsync();
        foreach (var groupCode in groupCodeList)
        {
            var userGroup = new FrameworkUserGroup
            {
                UserCode = user.ITCode,
                GroupCode = groupCode,
                TenantCode = Wtm.LoginUserInfo?.CurrentTenant,
                CreateBy = Wtm.LoginUserInfo?.ITCode,
                CreateTime = DateTime.Now,
                UpdateBy = Wtm.LoginUserInfo?.ITCode,
                UpdateTime = DateTime.Now
            };
            await DC.Set<FrameworkUserGroup>().AddAsync(userGroup);
        }

        // 删除用户原有的角色信息
        await DC.Set<FrameworkUserRole>()
            .Where(e => e.UserCode == user.ITCode)
            .ExecuteDeleteAsync();
        // 添加用户新的角色信息
        // 查询用户所有的岗位ID
        var jobPositionIds = await DC.Set<SysUserJobPosition>()
            .Where(e => e.UserId == userId)
            .Select(e => e.JobPositionId)
            .ToListAsync();
        // 查询岗位对应的角色代码
        var roleCodes = await DC.Set<SysJobPositionRole>()
            .Where(e => jobPositionIds.Contains(e.JobPositionId))
            .Select(e => e.Role.RoleCode)
            .Distinct()
            .ToListAsync();
        // 添加用户新的角色信息
        foreach (var roleCode in roleCodes)
        {
            var userRole = new FrameworkUserRole
            {
                UserCode = user.ITCode,
                RoleCode = roleCode,
                TenantCode = Wtm.LoginUserInfo?.CurrentTenant,
                CreateBy = Wtm.LoginUserInfo?.ITCode,
                CreateTime = DateTime.Now,
                UpdateBy = Wtm.LoginUserInfo?.ITCode,
                UpdateTime = DateTime.Now
            };
            await DC.Set<FrameworkUserRole>().AddAsync(userRole);
        }

        // 更新用户的更新时间和更新人，确保增量同步能识别到变更
        await DC.Set<FrameworkUser>()
            .Where(e => e.ID == userId)
            .ExecuteUpdateAsync(e =>
                e.SetProperty(x => x.UpdateTime, x => DateTime.Now)
                    .SetProperty(x => x.UpdateBy, x => Wtm.LoginUserInfo.ITCode));

        await DC.SaveChangesAsync();
        await Wtm.RemoveUserCache([user.ITCode]);
        Wtm.ClearUserPrivilegeCache(userId);
    }

    public override async Task DoEditAsync(bool updateAllFields = false)
    {
        var transaction = DC.BeginTransaction();
        try
        {
            if (Entity.UserId == null)
            {
                MSD.AddModelError("Entity.UserId", "用户不能为空");
                return;
            }

            if (Entity.IsMain)
            {
                await DC.Set<SysUserJobPosition>()
                    .Where(e => e.UserId == Entity.UserId)
                    .ExecuteUpdateAsync(e =>
                        e.SetProperty(x => x.IsMain, x => false));
                await DC.SaveChangesAsync();
            }

            await base.DoEditAsync(updateAllFields);
            await UpdateUserGroupAsync(Entity.UserId.Value);
            await transaction.CommitAsync();
        }
        catch (Exception e)
        {
            var scope = Wtm.ServiceProvider.CreateScope();
            var logger = scope.ServiceProvider.GetRequiredService<ILogger<SysUserJobPositionVm>>();
            logger.LogError(e, $"用户编辑岗位发生异常, {e.Message}");
            MSD.AddModelError(" ", $"编辑操作异常: {e.Message}");
            await transaction.RollbackAsync();
        }
        finally
        {
            await transaction.DisposeAsync();
        }
    }
}